<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属课程" prop="courseId">
        <el-select v-model="queryParams.courseId" placeholder="请选择" clearable @change="handleChangeCoures">
          <el-option v-for="item in selectCourses" :key="item.courseId" :label="item.courseName"
            :value="item.courseId" />
        </el-select>
      </el-form-item>
      <el-form-item label="考试班级" prop="classId">
        <el-select v-model="queryParams.classId" placeholder="请选择" clearable @change="handleChangeClass"
          @focus="handleClassFocus">
          <el-option v-for="item in selectClasses" :key="item.classId" :label="item.className" :value="item.classId" />
        </el-select>
      </el-form-item>
      <el-form-item label="考试题目" prop="exameId">
        <el-select v-model="queryParams.exameId" placeholder="请选择" clearable @focus="handleExameFocus">
          <el-option v-for="item in selectExames" :key="item.exameId" :label="item.exameTitle" :value="item.exameId" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="examePro">
        <el-select v-model="queryParams.examePro" placeholder="请选择" clearable>
          <el-option v-for="item in scoreStatus" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="Promotion" @click="handlePublish"
          v-hasPermi="['exam:theoryScore:publish']">成绩发布</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="classzList" @selection-change="handleSelectionChange">
      <!-- 考试名称、考试类型、课程名称、考试班级、学员姓名、考试时间、
       状态（0 未开始，1 进行中，2 审批中，3 已发布 、
       班主任、理论成绩、实操成绩； -->
      <el-table-column label="考试名称" align="center" prop="exameTitle" />
      <!-- <el-table-column label="考试类型" align="center" prop="exameTypeName" /> -->
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="考试班级" align="center" prop="className" />
      <el-table-column label="学员姓名" align="center" prop="stuName" />
      <el-table-column label="考试时间" align="center" prop="paperTime" />
      <el-table-column label="状态" align="center" prop="exameProName" />
      <el-table-column label="班主任" align="center" prop="teacherName" />
      <el-table-column label="理论成绩" align="center" prop="llScore" />
      <el-table-column label="实操成绩" align="center" prop="sjScore" />
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script setup name="Classz">
import { queryCourseList } from '@/api/analyse.js'
import { listExame } from "@/api/exam/exame";
import { queryClassByCourseId } from "@/api/register/registerList.js";
import {
  listTheoryScore,
  updateStatus
} from '@/api/scoreManager'

import { scoreStatus } from './status'
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted } from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute()
const { proxy } = getCurrentInstance();
// 下拉数据列表
const selectExames = ref([])
const selectClasses = ref([])
const selectCourses = ref([])
// 
const classzList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    exameId: null,
    classId: null,
    courseId: null,
    examePro: null,
  },
});

const { queryParams } = toRefs(data);

onMounted(() => {
  getSelectList()
  queryParams.value.courseId = route.query.courseId ? Number(route.query.courseId) : null
  if (queryParams.value.courseId && queryParams.value.courseId !== '') {
    queryClassByCourseId({ courseId: queryParams.value.courseId }).then(response => {
      if (response.code === 200) {
        selectClasses.value = response.data
      }
    });
  }
  queryParams.value.classId = route.query.classId ? Number(route.query.classId) : null
  if (queryParams.value.classId && queryParams.value.classId !== '') {
   handleChangeClass()
  }
  getList();
})

// 发布试卷
const handlePublish = () => {
  if (!queryParams.value.classId || queryParams.value.classId === '') {
    ElMessage.warning('请选择发布班级')
    return
  }
  
  if (!queryParams.value.exameId || queryParams.value.exameId === '') {
    ElMessage.warning('请选择发布考试题目')
    return
  }
  const index = selectClasses.value.findIndex(i => i.classId === queryParams.value.classId)
  ElMessageBox.confirm(`是否确认发布“${selectClasses.value[index].className}”成绩`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await updateStatus({ classId: queryParams.value.classId, exameId: queryParams.value.exameId  })
      if (res.code === 200) {
        ElMessage.success('成绩发布成功')
        getList()
      }
    })
    .catch(() => { });
}
// change事件
const handleChangeCoures = (item) => {
  console.log("🚀 ~ handleChangeCoures ~ item:", item)
  queryParams.value.classId = null
  selectClasses.value = []
  queryParams.value.exameId = null
  selectExames.value = []
  queryClassByCourseId({ courseId: queryParams.value.courseId }).then(response => {
    if (response.code === 200) {
      selectClasses.value = response.data
    }
  });
}
const handleClassFocus = () => {
  if (!queryParams.value.courseId || queryParams.value.courseId === '') {
    ElMessage.warning('请选择课程')
    return
  }
}
const handleChangeClass = (item) => {
  queryParams.value.exameId = null
  selectExames.value = []
  listExame({
    courseId: queryParams.value.courseId,
    classId: queryParams.value.classId,
    pageNum: 1,
    pageSize: 1000,
  }).then(response => {
    if (response.code === 200) {
      selectExames.value = response.rows
    }
  });
}
const handleExameFocus = () => {
  if (!queryParams.value.classId || queryParams.value.classId === '') {
    ElMessage.warning('请选择班级')
    return
  }
}
// 获取下拉
const getSelectList = () => {
  queryCourseList().then(response => {
    if (response.code === 200) {
      selectCourses.value = response.rows
    }
  });
}
/** 查询班级管理列表 */
function getList() {
  loading.value = true;
  listTheoryScore(queryParams.value).then(response => {
    classzList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.classId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('exam/theoryScore/export', {
    ...queryParams.value
  }, `成绩_${new Date().getTime()}.xlsx`)
}

</script>
